package com.atguigu.gmall.common.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.entity.GmallCorrelationData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;


@Component
@Slf4j
public class MQProducerAckConfig implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RedisTemplate redisTemplate;

    public MQProducerAckConfig(RabbitTemplate rabbitTemplate) {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }

    //交换机
    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        if (b){
            System.out.println("成功应答：原因是 : "+s);
        }else {
            System.out.println("失败应答：原因是 : "+s);
            //重新发送
            retrySendMessage(correlationData);
        }
    }




    //队列
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {

        System.out.println("message : "+new String(message.getBody()));
        System.out.println("replyCode : "+replyCode);
        System.out.println("replyText : "+replyText);
        System.out.println("exchange : "+exchange);
        System.out.println("routingKey : "+routingKey);

        Object uuid = message.getMessageProperties().getHeader("spring_returned_message_correlation");
        String rabbit_prefix = (String) redisTemplate.opsForHash().get("rabbit_prefix", uuid);
        GmallCorrelationData gmallCorrelationData = JSONObject.parseObject(rabbit_prefix, GmallCorrelationData.class);
        if(gmallCorrelationData.isDelay()){
            return;
        }
        retrySendMessage(gmallCorrelationData);
    }

    //重新发送
    public void retrySendMessage(CorrelationData correlationData){
        GmallCorrelationData correlationData1 = (GmallCorrelationData) correlationData;
        int retryCount = correlationData1.getRetryCount();
        retryCount++;
        if (retryCount <= 2) {
            redisTemplate.opsForHash().put("rabbit_prefix",correlationData1.getId(),JSON.toJSONString(correlationData1));
            log.info("成功重新发送:{}"+ JSON.toJSONString(correlationData1));
            rabbitTemplate.convertAndSend(correlationData1.getExchange(),correlationData1.getRoutingKey()
                                        ,correlationData1.getMessage(),correlationData1);
        }else {
            log.info("剩余发送次数已经用完:{}"+JSON.toJSONString(correlationData1));
        }
    }
}
